package org.adream.account.service;

import java.util.Date;
import java.util.List;

import org.adream.account.aop.annotation.DataSource;
import org.adream.account.dao.Dream2020CertificationDao;
import org.adream.account.dao.Dream2020RoleUserLinkDao;
import org.adream.account.dao.Dream2020SchoolDao;
import org.adream.account.dao.Dream2020UserDao;
import org.adream.account.entity.Dream2020CertificationEntity;
import org.adream.account.entity.Dream2020SchoolEntity;
import org.adream.account.entity.Dream2020UserEntity;
import org.adream.account.model.ResultModel;
import org.adream.account.util.Constant;
import org.adream.account.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

@Service
@DataSource("adreambox2020DataSource")
public class Dream2020SchoolService {
	
	@Autowired
	private Dream2020SchoolDao dream2020SchoolDao;
	
	@Autowired
	private Dream2020UserDao dream2020UserDao;
	
	@Autowired
	private Dream2020RoleUserLinkDao dream2020RoleUserLinkDao;
	
	@Autowired
	private Dream2020CertificationDao dream2020CertificationDao;
	
	private final static Logger logger = LoggerFactory.getLogger(Dream2020SchoolService.class);
	
	/**
	 * 新增或更新新版盒子学校
	 * @param dream2020SchoolEntity
	 * @return
	 * @throws ADreamServiceException
	 */
	public ResultModel<String> addOrUpdateDream2020School(Dream2020SchoolEntity dream2020SchoolEntity) throws ADreamServiceException {
		//1.先根据school_number查询更新
		List<Dream2020SchoolEntity> dream2020SchoolNumberSchools = dream2020SchoolDao.queryDream2020SchoolsBySchoolNumber(dream2020SchoolEntity.getSchoolNumber());
		if(!Utils.isEmptyCollection(dream2020SchoolNumberSchools)) {
			if(dream2020SchoolNumberSchools.size() > 1) {
				logger.warn("更新新版盒子学校失败,school_number:" + dream2020SchoolEntity.getSchoolNumber() + "对应多个学校:(");
				return new ResultModel<String>(ResultModel.HAS_FOUND_OBJECT, "更新失败,学校编码对应对个学校", null);
			}
			dealDream2020SchoolData(dream2020SchoolEntity, dream2020SchoolNumberSchools.get(0));
			return new ResultModel<String>(ResultModel.SUCCESS, "更新成功", null);
		} else {
			//2.再根据email查询更新,更改了school_number
			List<Dream2020SchoolEntity> dream2020EmailSchools = dream2020SchoolDao.queryDream2020SchoolsByEmail(dream2020SchoolEntity.getEmail());
			if(!Utils.isEmptyCollection(dream2020EmailSchools)) {
				if(dream2020EmailSchools.size() > 1) {
					logger.warn("更新新版盒子学校失败,email:" + dream2020SchoolEntity.getEmail() + "存在多个学校:(");
					return new ResultModel<String>(ResultModel.HAS_FOUND_OBJECT, "更新失败,邮箱对应多个学校", null);
				}
				dealDream2020SchoolData(dream2020SchoolEntity, dream2020EmailSchools.get(0));
				return new ResultModel<String>(ResultModel.SUCCESS, "更新成功", null);
			} else {
				//3.再根据sname查询更新,更改了school_number
				List<Dream2020SchoolEntity> dream2020SnameSchools = dream2020SchoolDao.queryDream2020SchoolsByName(dream2020SchoolEntity.getName());
				if(!Utils.isEmptyCollection(dream2020SnameSchools)) {
					if(dream2020SnameSchools.size() > 1) {
						logger.warn("更新新版盒子学校失败,sname:" + dream2020SchoolEntity.getName() + "存在多个学校:(");
						return new ResultModel<String>(ResultModel.HAS_FOUND_OBJECT, "更新失败,学校名称对应多个学校", null);
					}
					dealDream2020SchoolData(dream2020SchoolEntity, dream2020SnameSchools.get(0));					
					return new ResultModel<String>(ResultModel.SUCCESS, "更新成功", null);
				} else {
					//4.根据school_number,email,sname未查询到相应的学校数据,即是新学校
					List<Dream2020UserEntity> dream2020EmailUsers = dream2020UserDao.queryDream2020UsersByEmail(dream2020SchoolEntity.getEmail());
					int uid = 0;
					if(!Utils.isEmptyCollection(dream2020EmailUsers)) {
						if(dream2020EmailUsers.size() > 1) {
							logger.warn("更新新版盒子学校失败,email:" + dream2020SchoolEntity.getEmail() + "存在多个用户:(");
							return new ResultModel<String>(ResultModel.HAS_FOUND_OBJECT, "更新失败,邮箱对应多个用户", null);
						}
						uid = dream2020EmailUsers.get(0).getId();
					} else {
						//不存在学校账号,则创建学校账号
						Dream2020UserEntity dream2020User = new Dream2020UserEntity();
						dream2020User.setName(dream2020SchoolEntity.getName());
						dream2020User.setEmail(dream2020SchoolEntity.getEmail());
						dream2020User.setPassword("RegByCas");
						dream2020User.setLocation(dream2020SchoolEntity.getLocation());
						dream2020User.setCreatedAt(new Date());
						dream2020User.setUpdatedAt(new Date());
						int addDream2020UserResult = dream2020UserDao.addDream2020User(dream2020User);
						if(addDream2020UserResult == Constant.ZERO) {
							logger.warn("新增新版盒子学校账号记录失败,数据库错误:(");
							throw new ADreamServiceException("系统错误0119-2,请联系系统管理员");
						}
						uid = dream2020User.getId();
					}
					//判断是否包含'梦想中心学校'角色
					if(dream2020SchoolEntity.isAdreamCenter()) {						
						//学校账号添加'梦想中心'角色
						int replaceDream2020RoleUserResult = dream2020RoleUserLinkDao.replaceDream2020RoleUser(uid, Constant.DREAM_2020_USER_GROUP_DREAM_ROLE_ID);
						if(replaceDream2020RoleUserResult == Constant.ZERO) {
							logger.warn("添加新版盒子学校账号'梦想中心'角色失败,数据库错误");
							throw new ADreamServiceException("系统错误0119-3,请联系系统管理员");
						}
					}
					//新版盒子数据库不存在当前学校记录
					int addDream2020SchoolResult = dream2020SchoolDao.addDream2020School(dream2020SchoolEntity);
					if(addDream2020SchoolResult == Constant.ZERO) {
						logger.warn("添加新版盒子学校记录失败,数据库错误:(");
						throw new ADreamServiceException("系统错误0119-4,请联系系统管理员");
					}
					int sid = dream2020SchoolEntity.getId();
					//新增认证记录
					Dream2020CertificationEntity dream2020Certification = new Dream2020CertificationEntity();
					dream2020Certification.setCertificationName("other");
					dream2020Certification.setUserId(uid);
					dream2020Certification.setSid(sid);
					JSONObject data = new JSONObject();
					data.put("name", dream2020SchoolEntity.getName());
					data.put("phone", dream2020SchoolEntity.getPhone());
					data.put("realname", dream2020SchoolEntity.getName());
					data.put("desc", "学校账号");
					dream2020Certification.setData(data.toString());
					dream2020Certification.setExaminer(uid);
					//认证状态设为'认证通过'
					dream2020Certification.setStatus(Constant.ONE);
					dream2020Certification.setCreatedAt(new Date());
					dream2020Certification.setUpdatedAt(new Date());
					//type等于1时为学校账号
					dream2020Certification.setType(Constant.ONE);
					//设置为新版盒子'梦想中心'角色id
					dream2020Certification.setRolesId(Constant.DREAM_2020_USER_GROUP_DREAM_ROLE_ID);
					int addDream2020CertificationResult = dream2020CertificationDao.addDream2020Certification(dream2020Certification);
					if(addDream2020CertificationResult == Constant.ZERO) {
						logger.warn("添加新版盒子认证记录失败,数据库错误:(");
						throw new ADreamServiceException("系统错误0119-5,请联系系统管理员");
					}
					return new ResultModel<String>(ResultModel.SUCCESS, "新增学校成功", null);
				}
			}
		}
	}
	
	/**
	 * 处理新版盒子学校数据
	 * @param dream2020SchoolEntity
	 * @param dream2020School
	 * @throws ADreamServiceException
	 */
	private void dealDream2020SchoolData(Dream2020SchoolEntity dream2020SchoolEntity, Dream2020SchoolEntity dream2020School) throws ADreamServiceException {
		int id = dream2020School.getId();
		Utils.copyPropertiesIgnoreNull(dream2020SchoolEntity, dream2020School);
		dream2020School.setId(id);
		dream2020School.setMtime(new Date());
		int result = dream2020SchoolDao.updateDream2020School(dream2020School);
		if(result == Constant.ZERO) {
			logger.warn("更新新版盒子学校失败,数据库错误:(");
			throw new ADreamServiceException("系统错误0119,请联系系统管理员");
		}
		List<Dream2020CertificationEntity> dream2020Certifications = dream2020CertificationDao.queryDream2020CertificationsBySidAndType(dream2020School.getId(), Constant.ONE);
		if(!Utils.isEmptyCollection(dream2020Certifications)) {
			if(dream2020Certifications.size() > 1) {
				logger.warn("更新新版盒子学校失败,school_number:" + dream2020SchoolEntity.getSchoolNumber() + "存在多条认证记录:(");
				throw new ADreamServiceException("更新失败,学校对应多条认证记录");
			}
			Dream2020CertificationEntity dream2020Certification = dream2020Certifications.get(0);
			if(dream2020SchoolEntity.getIsDel() == Constant.ONE) {
				//该学校已删除,暂时只删除该学校的认证,学校账号的梦想中心角色,学校认证梦想教师先不删除(考虑到同步到的学校数据可能出现有效、删除交替)
				dream2020Certification.setIsDel(Constant.ONE);
				int deleteDream2020CertificaionResult = dream2020CertificationDao.deleteDream2020CertificationBySidAndType(dream2020Certification);
				if(deleteDream2020CertificaionResult == Constant.ZERO) {
					logger.warn("更新新版盒子学校认证表失败,数据库错误:(");
					throw new ADreamServiceException("系统错误0119-1,请联系系统管理员");
				}
				//删除学校账号'梦想中心'角色
				dream2020RoleUserLinkDao.deleteDream2020RoleUser(dream2020Certification.getUserId(), Constant.DREAM_2020_USER_GROUP_DREAM_ROLE_ID);
			} else {
				//更新认证信息
				dream2020Certification.setCertificationName("other");
				JSONObject data = new JSONObject();
				data.put("name", dream2020SchoolEntity.getName());
				data.put("phone", dream2020SchoolEntity.getPhone());
				data.put("realname", dream2020SchoolEntity.getName());
				data.put("desc", "学校账号");
				dream2020Certification.setData(data.toString());
				dream2020Certification.setType(Constant.ONE);
				dream2020Certification.setRolesId(Constant.DREAM_2020_USER_GROUP_DREAM_ROLE_ID);
				dream2020Certification.setIsDel(Constant.ZERO);
				int updateDream2020CertificationResult = dream2020CertificationDao.updateDream2020Certificayion(dream2020Certification);
				if(updateDream2020CertificationResult == Constant.ZERO) {
					logger.warn("更新新版盒子学校认证表失败,数据库错误:(");
					throw new ADreamServiceException("系统错误0119-6,请联系系统管理员");
				}
				//判断是否包含'梦想中心学校'角色
				if(dream2020SchoolEntity.isAdreamCenter()) {					
					//添加学校账户'梦想中心'角色
					dream2020RoleUserLinkDao.replaceDream2020RoleUser(dream2020Certification.getUserId(), Constant.DREAM_2020_USER_GROUP_DREAM_ROLE_ID);
				}
				//更新学校账号昵称信息
				dream2020UserDao.updateDream2020UserNameById(dream2020SchoolEntity.getName(), dream2020Certification.getUserId());
			}
		}
	}
}